"""
Put this file in the dir which you want to change file encode
    OK, this begin
"""
import os
import glob

#set your file dir
FILE_ENCODE_DIR = ""
FILE_ENCODE_DIR_LIST = ["",]
_dir_list_all = [".",]

#specify file list
_specify_file_list = []

#encode & decode setting
DECODE = "gb2312"
ENCODE = "utf-8"
"""
dir_list = [os.path.normcase(f)
                for f in os.listdir(FILE_ENCODE_DIR)
                    if os.path.isdir(os.path.join(FILE_ENCODE_DIR, f))]
                    
file_list = [os.path.normcase(f)
                for f in os.listdir(FILE_ENCODE_DIR)
                    if os.path.isfile(os.path.join(FILE_ENCODE_DIR, f))]
                    
specify_file_list = glob.glob("%s*.php"%(FILE_ENCODE_DIR))

print dir_list,file_list,specify_file_list

for file in specify_file_list:
    f = open(file)
    f.seek(0, 0)
    f_content = f.read()
    f_content_encode = f_content.decode("euc-jp").encode("UTF-8")
    f.close()
    
    try: 
        f_write = open(file,"w")
        f_write.write(f_content_encode)
        f_write.close()
    except IOError:
        pass    
    
print "files encodeing had finished"
"""

def main(dir_list):
    global _specify_file_list

    get_dir_son_list(dir_list)
    #print _dir_list_all
    for dir in _dir_list_all:
        specify_file_list = glob.glob("%s/*.py"%(dir))
        _specify_file_list.extend(specify_file_list)

    encode_file(_specify_file_list)

#get the dir list
def get_dir_son_list(dir_list):
    global _dir_list_all
    for dir in dir_list:
        dir_son_list = [os.path.join(dir, f)
                        for f in os.listdir(dir)
                            if os.path.isdir(os.path.join(dir, f))]
        #print dir_son_list--add all dir into _dir_list_all
        _dir_list_all.extend(dir_son_list)
        #recursion
        get_dir_son_list(dir_son_list)

def encode_file(specify_file_list):
    for file in specify_file_list:
        f = open(file)
        f.seek(0, 0)
        f_content = f.read()
        f_content_encode = f_content.decode(DECODE).encode(ENCODE)
        f.close()

        try: 
            f_write = open(file,"w")
            f_write.write(f_content_encode)
            f_write.close()

        except IOError:
            print file+":read only; "

main(FILE_ENCODE_DIR_LIST)
print "encoding end"